package com.cainaer.common.security.config;

import com.cainaer.common.core.utils.DateUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.naming.AuthenticationException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author-> tina
 * @date-> 2020/9/2 下午12:08
 * @version-> 1.0
 * @description-> 无效token 异常重写
 **/
@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, org.springframework.security.core.AuthenticationException e) throws IOException, ServletException {
        Map<String, Object> map = new HashMap<String, Object>();
        Throwable cause = e.getCause();
        if (cause instanceof InvalidTokenException) {
            map.put("code", 401);//401
            map.put("msg", "无效的token");
        } else {
            map.put("code", 401);//401
            map.put("msg", "访问此资源需要完全的身份验证");
        }
        map.put("data", e.getMessage());
        map.put("success", false);
        map.put("path", httpServletRequest.getServletPath());
        map.put("timestamp", DateUtils.dateTime());
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(httpServletResponse.getOutputStream(), map);
        } catch (Exception ex) {
            throw new ServletException();
        }
    }
}
